package com.gzc.just.play.last.war.allinone.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * All-in-One启动完成监听器
 * 在所有Spring Bean初始化完成后，确保核心服务器已经启动
 */
@Component
public class AllInOneStartupListener {
    private static final Logger logger = LoggerFactory.getLogger(AllInOneStartupListener.class);
    
    /**
     * 监听应用启动完成事件
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady(ApplicationReadyEvent event) {
        logger.info("============================================================");
        logger.info("All-in-One Server Application is ready");
        logger.info("All core servers should now be running:");
        logger.info("  - LoginServer on port 30001");
        logger.info("  - GateServer on port 40001");
        logger.info("  - SceneServer on port 50001");
        logger.info("  - CentralServer on port 6001");
        logger.info("  - BalanceServer on port 7001");
        logger.info("  - HTTP Server on port 8088");
        logger.info("============================================================");
        
        // 尝试验证关键服务器的可用性
        verifyServersStartup(event);
    }
    
    /**
     * 验证关键服务器是否已启动
     */
    private void verifyServersStartup(ApplicationReadyEvent event) {
        try {
            // 尝试获取SceneNettyServer Bean（通过反射避免直接导入）
            Object sceneServer = event.getApplicationContext().getBean("sceneNettyServer");
            if (sceneServer != null) {
                logger.info("SceneServer bean initialized successfully");
            }
            
            // 尝试获取GateNettyServer Bean（通过反射避免直接导入）
            Object gateServer = event.getApplicationContext().getBean("gateNettyServer");
            if (gateServer != null) {
                logger.info("GateServer bean initialized successfully");
            }
            
            // 尝试获取BalanceNettyServer Bean（通过反射避免直接导入）
            Object balanceServer = event.getApplicationContext().getBean("balanceNettyServer");
            if (balanceServer != null) {
                logger.info("BalanceServer bean initialized successfully");
            }
        } catch (Exception e) {
            logger.warn("Could not verify all servers during startup check: {}", e.getMessage());
        }
    }
}
